//子页面的index的key
// ignore_for_file: constant_identifier_names

import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/novel_detail_page.dart';
import 'package:tiktokadult/hj_page/mine_business/ai/ai_home_menu_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/bing_phone_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_coin_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_vip_page.dart';
import 'package:tiktokadult/hj_page/mine_business/welfare/welfare_home_page.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_page.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_page/user_center_page/user_center_page.dart';
import 'package:tiktokadult/hj_page/video/video_page.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/event_bus/events.dart';
import 'package:tiktokadult/tools_base/loading/LoadingHelper.dart';

import '../config/config.dart';
import '../hj_model/cartoon_media_info.dart';
import '../hj_page/cartoon_business/cartoon_detail_page.dart';
import '../hj_page/community_business/post_detail_page/post_detail_page.dart';
import '../hj_page/community_business/publish_page/publish_page.dart';
import '../hj_page/find/rank_module/rank_main_page.dart';
import '../hj_page/mine_business/message/message_center_page.dart';
import '../hj_page/mine_business/mine_share/mine_share_page.dart';
import '../hj_page/mine_business/mine_utils.dart';
import '../hj_page/short_video/short_video_page.dart';
import '../hj_page/web_page/h5_page.dart';
import '../hj_utils/api_service/common_service.dart';
import '../hj_utils/api_service/vid_service.dart';
import '../tools_base/event_bus/event_bus_util.dart';

const String KEY_SUB_PAGE = "sub_page";

/*
isCartoon 是否是动漫类型,
videoModel 视频数据模型，
videoId 视频id，
videoArr 短视频跳转可能需要
isShort 是否是短视频
备注：视频信息 videoModel/videoId 两个必须传一个(数据有model就传model，有可能需要其他数据来处理不同的业务)
*/
Future? pushToVideoPage({
  String? videoId,
  VideoModel? videoModel,
  bool isCartoon = false,
  String? videoCover,
  List<VideoModel>? videoArr,
  bool toVideo = false, // 帖子详情跳视频
  int videoFctIndex = 0,
}) {
  /// 优先动漫
  if (isCartoon == true) {
    //动漫跳长视频
    return Get.to(
      VideoPage(
        id: videoModel?.id ?? videoId,
        isCartoon: true,
        videoCover: videoCover ?? videoModel?.cover,
      ),
      preventDuplicates: false,
    );
  } else if (((videoModel?.playTime ?? 1000) < 300 && videoModel?.playTime != 0)) {
    // 跳短视频
    int index = 0;
    if (videoArr?.isNotEmpty != true && videoModel != null) {
      videoArr = [videoModel];
    }
    for (int i = 0; i < (videoArr?.length ?? 0); i++) {
      if (videoArr![i].id == videoModel?.id) {
        index = i;
        break;
      }
    }
    return Get.to(
      ShortVideoPage(
        type: VideoListType.SECOND,
        videoList: videoArr ?? [videoModel!],
        pageIndex: index,
      ),
      preventDuplicates: false,
    );
  }
  return Get.to(VideoPage(
    id: videoId ?? videoModel?.id,
    videoCover: videoCover ?? videoModel?.cover,
    model: videoModel,
  ));
}

//跳转卡通详情
pushToCartoonPage(CartoonMediaInfo? info) {
  final mediaType = info?.mediaType ?? '';
  if (mediaType == 'image') {
    Get.to(
        CartoonDetailPage(
          id: info?.id ?? '',
          heroTag: info?.heroTag,
        ),
        preventDuplicates: false);
  } else if (mediaType == 'text') {
    Get.toNamed(
      NovelDetailPage.routeName,
      arguments: info?.id,
      preventDuplicates: false,
    );
  } else if (mediaType == 'video') {
    //跳转到视频详情页
    pushToVideoPage(
      videoId: info?.id ?? '',
      isCartoon: true,
      videoCover: info?.coverV,
    );
  }
  // else if () {
  //   Get.toNamed(
  //     NovelDetailPage.routeName,
  //     arguments: info?.id,
  //     preventDuplicates: false,
  //   );
  // }
}

Future? pushToPageByLink(String? url, {String? id, Map<String, dynamic>? arguments}) async {
  if (url?.isNotEmpty != true) return null;
  Uri? uri;
  try {
    uri = Uri.parse(url!);
  } catch (e) {
    debugLog("go func", e.toString());
  }
  arguments ??= {};
  arguments.addAll(uri?.queryParameters ?? {});
  if (uri == null) {
    return null;
  }
  try {
    if (id?.isNotEmpty == true) {
      CommonService.clickADEvent(id ?? "");
    }
  } catch (e) {
    debugLog("go func", e.toString());
  }
  String host_ = uri.host.toLowerCase();
  final host = host_.removeAllWhitespace;

  if (uri.scheme == "yinseinner") {
    if (host == "submodule") {
      //亚模块分类
      eventBus.emit(YinseinnerModel(routeName: "module", id: arguments["id"]));
    } else if (host == "navigation_bar") {
      //导航栏 亚模块菜单弹出
      eventBus.emit(YinseinnerModel(routeName: "navigation_bar"));
    } else if (host == "community_module") {
      // 社区
      eventBus.emit(YinseinnerModel(routeName: "community_module", id: arguments["id"]));
    } else if (host == "vip_page") {
      return jumpToWalletPage(vipId: arguments['id']); // 会员中心
    } else if (host == "wallet_page") {
      //金币购买
      return jumpToWalletPage(tabPosition: 1);
    } else if (host == "universal_agent") {
      //分享推广
      return Get.to(() => MineSharePage(), preventDuplicates: false);
    } else if (host == 'lottery') {
      presaleProvider.gotoLuckydraw();
    } else if (host == "rankinglist") {
      return Get.to(RankMainPage(), preventDuplicates: false);
    } else if (host == "postdetail") {
      //帖子详情
      return Get.toNamed(PostDetailPage.routeName, arguments: PostDetailPageArgument(id: arguments["id"]));
    } else if (host == "video_page") {
      //长视频播放页
      return Get.to(VideoPage(id: arguments["id"]), preventDuplicates: false);
    } else if (host == "taskhall") {
      //福利任务
      return Get.to(WelfareHomePage(), preventDuplicates: false, arguments: 1);
    } else if (host == 'advancepage') {
      // 预售
      Get.toNamed(PreSalePage.routeName);
    } else if (host == "science") {
      //AI科技
      return Get.to(() => AiHomeMenuPage(), preventDuplicates: false);
    } else if (host == "live_streaming") {
      //直播
      eventBus.emit(YinseinnerModel(routeName: "live_streaming"));
    } else if (host == "shop_page") {
      //原味商店
      if (Config.storeIsOpen == true) {
        try {
          LoadingHelper.showLoading();
          var result = await VidService.getRemoteShopAddress();
          LoadingHelper.dismissLoading();
          if (result is String && result.isNotEmpty != true) {
            showToast("获取商店地址失败～");
            return;
          }
          return Get.to(H5Page(url: result), popGesture: true);
        } catch (e) {
          LoadingHelper.dismissLoading();
          debugLog(e);
        }
      }
    } else if (host == "kefu") {
      //在线客服
      MineUtils.goCSPage();
    } else if (host == "userhomepage") {
      //跳转博主
      int uid = arguments["uid"] ?? 0;
      if (uid == 0) {
        return;
      }
      return pushToPersonCenter(uid);
    } else if (host == 'publish_page') {
      // 发布
      return Get.toNamed(PublishPage.routeName, arguments: PublishType.homeImgText);
    } else if (host == 'binding_page') {
      //绑定手机
      return Get.toNamed(BindPhonePage.routeName, arguments: PhonePageType.bind);
    } else {
      showToast("未处理链接");
    }
  } else if (uri.scheme.startsWith("http")) {
    return launchUrlToWeb(url!);
  } else {
    showToast("未知链接");
  }
  return null;
}

///浏览器跳转
Future launchUrlToWeb(String url, {String? tip}) async {
  try {
    await launchUrl(Uri.parse(url), mode: LaunchMode.externalNonBrowserApplication);
    if (tip?.isNotEmpty == true) {
      showToast(tip!);
    }
  } catch (e) {
    debugLog(e);
  }
}

Future? pushToPersonCenter(dynamic id, {int? type}) {
  if (type == 1) {
    // return Get.to(ActressMainPage(), arguments: {"uid": id}, preventDuplicates: false);
  } else {
    return Get.toNamed(UserCenterPage.routeName, arguments: {"uid": id, "type": type}, preventDuplicates: false);
  }
}

Future jumpToWalletPage({int? tabPosition, String? vipId}) async {
  if (tabPosition == 1) {
    return Get.to(MineChargeCoinPage(), preventDuplicates: false);
  } else {
    return Get.to(MineChargeVipPage(), arguments: vipId, preventDuplicates: false);
  }
}
